package com.example.servlet;

import com.example.bean.Medicine;
import com.example.service.MedicineService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 药材管理Servlet
 * 使用JSP + Servlet + JavaBean架构
 * Servlet作为控制器，调用Service层（JavaBean）处理业务逻辑
 */
@WebServlet("/medicine")
public class MedicineServlet extends HttpServlet {

    // 使用Service层（JavaBean）而不是直接使用DAO
    private MedicineService medicineService = new MedicineService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");
        
        if (action == null) {
            action = "list";
        }
        
        switch (action) {
            case "list":
                listMedicines(request, response);
                break;
            case "detail":
                showDetail(request, response);
                break;
            case "add":
                showAddForm(request, response);
                break;
            case "edit":
                showEditForm(request, response);
                break;
            case "delete":
                deleteMedicine(request, response);
                break;
            case "search":
                searchMedicines(request, response);
                break;
            default:
                listMedicines(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");
        
        if ("save".equals(action)) {
            saveMedicine(request, response);
        } else if ("update".equals(action)) {
            updateMedicine(request, response);
        } else {
            doGet(request, response);
        }
    }

    /**
     * 显示药材列表
     */
    private void listMedicines(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 调用Service层（JavaBean）获取数据
        List<Medicine> medicines = medicineService.getAllMedicines();
        request.setAttribute("medicines", medicines);
        request.getRequestDispatcher("/medicineList.jsp").forward(request, response);
    }

    /**
     * 搜索药材
     */
    private void searchMedicines(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String keyword = request.getParameter("keyword");

        if (keyword == null || keyword.trim().isEmpty()) {
            listMedicines(request, response);
            return;
        }

        // 调用Service层（JavaBean）进行搜索
        List<Medicine> medicines = medicineService.searchMedicines(keyword.trim());
        request.setAttribute("medicines", medicines);
        request.setAttribute("keyword", keyword);
        request.getRequestDispatcher("/medicineList.jsp").forward(request, response);
    }

    /**
     * 显示药材详情
     */
    private void showDetail(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        // 调用Service层（JavaBean）获取数据
        Medicine medicine = medicineService.getMedicineById(id);

        if (medicine != null) {
            request.setAttribute("medicine", medicine);
            request.getRequestDispatcher("/medicineDetail.jsp").forward(request, response);
        } else {
            response.sendRedirect(request.getContextPath() + "/medicine?action=list");
        }
    }

    /**
     * 显示添加表单
     */
    private void showAddForm(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.getRequestDispatcher("/medicineForm.jsp").forward(request, response);
    }

    /**
     * 显示编辑表单
     */
    private void showEditForm(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        // 调用Service层（JavaBean）获取数据
        Medicine medicine = medicineService.getMedicineById(id);

        if (medicine != null) {
            request.setAttribute("medicine", medicine);
            request.getRequestDispatcher("/medicineForm.jsp").forward(request, response);
        } else {
            response.sendRedirect(request.getContextPath() + "/medicine?action=list");
        }
    }

    /**
     * 保存新药材
     */
    private void saveMedicine(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Medicine medicine = new Medicine();
        medicine.setMedicineNo(request.getParameter("medicineNo"));
        medicine.setMedicineName(request.getParameter("medicineName"));
        medicine.setAlias(request.getParameter("alias"));
        medicine.setSource(request.getParameter("source"));
        medicine.setEnvironment(request.getParameter("environment"));
        medicine.setNatureFlavor(request.getParameter("natureFlavor"));
        medicine.setMainFunction(request.getParameter("mainFunction"));
        medicine.setUsageDosage(request.getParameter("usageDosage"));

        // 调用Service层（JavaBean）处理业务逻辑
        if (medicineService.addMedicine(medicine)) {
            response.sendRedirect(request.getContextPath() + "/medicine?action=list");
        } else {
            request.setAttribute("error", "添加药材失败");
            request.setAttribute("medicine", medicine);
            request.getRequestDispatcher("/medicineForm.jsp").forward(request, response);
        }
    }

    /**
     * 更新药材
     */
    private void updateMedicine(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Medicine medicine = new Medicine();
        medicine.setId(Integer.parseInt(request.getParameter("id")));
        medicine.setMedicineNo(request.getParameter("medicineNo"));
        medicine.setMedicineName(request.getParameter("medicineName"));
        medicine.setAlias(request.getParameter("alias"));
        medicine.setSource(request.getParameter("source"));
        medicine.setEnvironment(request.getParameter("environment"));
        medicine.setNatureFlavor(request.getParameter("natureFlavor"));
        medicine.setMainFunction(request.getParameter("mainFunction"));
        medicine.setUsageDosage(request.getParameter("usageDosage"));

        // 调用Service层（JavaBean）处理业务逻辑
        if (medicineService.updateMedicine(medicine)) {
            response.sendRedirect(request.getContextPath() + "/medicine?action=list");
        } else {
            request.setAttribute("error", "更新药材失败");
            request.setAttribute("medicine", medicine);
            request.getRequestDispatcher("/medicineForm.jsp").forward(request, response);
        }
    }

    /**
     * 删除药材
     */
    private void deleteMedicine(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        // 调用Service层（JavaBean）处理业务逻辑
        medicineService.deleteMedicine(id);
        response.sendRedirect(request.getContextPath() + "/medicine?action=list");
    }
}

